package cn.xinfei.xdecision.config;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.convert.CustomConversions;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.*;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

@Configuration
public class MongoCustomerConfig implements ApplicationListener<ContextRefreshedEvent> {


    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
        MongoTemplate examMongoTemplate = applicationContext.getBean("examMongoTemplate", MongoTemplate.class);
        if (null != examMongoTemplate) {
            MongoConverter converter = examMongoTemplate.getConverter();
            if (converter.getTypeMapper().isTypeKey("_class")) {
                ((MappingMongoConverter) converter).setTypeMapper(new DefaultMongoTypeMapper(null));
            }
        }
        MongoTemplate mongoTemplate = applicationContext.getBean("mongoTemplate", MongoTemplate.class);
        if (null != mongoTemplate) {
            MongoConverter converter = mongoTemplate.getConverter();
            if (converter.getTypeMapper().isTypeKey("_class")) {
                ((MappingMongoConverter) converter).setTypeMapper(new DefaultMongoTypeMapper(null));
            }
        }

    }

    @Bean
    public MappingMongoConverter mappingMongoConverter(MongoDatabaseFactory factory, BeanFactory beanFactory) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
        MongoMappingContext context = new MongoMappingContext();
        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
        try {
            mappingConverter.setCustomConversions(beanFactory.getBean("mongoCustomConversions", CustomConversions.class));
        } catch (NoSuchBeanDefinitionException ignore) {
            ignore.printStackTrace();
        }

        // Don't save _class to mongo
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));

        return mappingConverter;
    }

}
